<template>
  <div class="werewolf-room">
    <!-- 顶部房间信息栏 -->
    <div class="room-header">
      <div class="room-info">
        <div class="room-avatar">🎭</div>
        <div class="room-details">
          <div class="room-title">
            <span class="game-icon">⏰</span>
            <span>{{ theaterData.theater_title }}</span>
          </div>
          <div class="room-status">
            <span class="status-item phase">
              <span class="status-dot"></span>
              {{ theaterData.node_title }}
            </span>
            <span class="status-item">👥 {{ allCharacters.length }}个角色</span>
            <span class="status-item">🎬 {{ getCurrentSpeakerName() }}发言中</span>
            <span class="status-item" v-if="sessionId">🔗 已连接</span>
          </div>
        </div>
      </div>
      <div class="room-actions">
        <button class="action-btn secondary" @click="handleSettings">
          <span class="icon">⚙️</span>
          <span>保存</span>
        </button>
        <button class="action-btn secondary" @click="handleRules">
          <span class="icon">📖</span>
          <span>剧情</span>
        </button>
        <button class="action-btn primary" @click="handleSkipTurn" :disabled="!canSkipTurn">
          <span class="icon">⏭️</span>
          <span>跳过发言</span>
        </button>
      </div>
    </div>

    <!-- 主内容区域 -->
    <div class="main-content">
      <!-- 左侧发言区域 -->
      <div class="speech-area">
        <!-- 当前发言者舞台 -->
        <div class="current-speaker-stage">
          <!-- 左侧剧情内容区域 -->
          <div class="script-section">
            <div class="script-header">
              <span class="script-icon">📜</span>
              <span class="script-title">{{ theaterData.node_title }}</span>
            </div>
            <div class="script-content">
              <div class="script-description" v-html="theaterData.node_content">
              </div>

              <!-- 当前玩家角色信息 -->
              <div class="player-role-info" v-if="currentPlayerCharacter">
                <div class="roles-title">您扮演的角色：</div>
                <div class="current-role">
                  <div class="role-avatar">
                    <img :src="currentPlayerCharacter.avatar" :alt="currentPlayerCharacter.name" />
                  </div>
                  <div class="role-details">
                    <div class="role-name">{{ currentPlayerCharacter.name }}</div>
                    <div class="role-desc">{{ currentPlayerCharacter.description }}</div>
                    <div class="role-skills">
                      <span class="skills-label">技能：</span>
                      <div class="skills-list">
                        <span
                          v-for="skill in currentPlayerCharacter.selectedSkills"
                          :key="skill"
                          class="skill-tag"
                        >
                          {{ skill }}
                        </span>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <!-- 右侧当前发言角色区域 -->
          <div class="speaker-section">
            <!-- 文字模式 -->
            <div v-if="textMode" class="text-mode-section">
              <div class="speaker-info">
                <div class="speaker-avatar">
                  <img
                    :src="currentSpeaker?.avatar"
                    :alt="currentSpeaker?.name"
                  />
                  <div class="role-indicator">🎭</div>
                </div>
                <div class="speaker-details">
                  <div class="speaker-name">{{ currentSpeaker?.name }}</div>
                  <div class="speaker-role">{{ getCharacterRole(currentSpeaker) }}</div>
                  <div class="speech-status">
                    <span v-if="isCurrentPlayerTurn">文字发言模式</span>
                    <span v-else>等待发言</span>
                  </div>
                </div>
              </div>

              <!-- 文字输入区域 -->
              <div class="text-input-area" v-if="isCurrentPlayerTurn">
                <div class="input-header">
                  <span class="input-icon">✍️</span>
                  <span class="input-title">输入您的发言内容</span>
                </div>
                <textarea
                  v-model="newMessage"
                  placeholder="请输入角色发言内容..."
                  class="text-input"
                  rows="4"
                  :disabled="isLoadingMessages"
                  @keydown.ctrl.enter="sendTextMessage"
                ></textarea>
                <div class="input-footer">
                  <span class="input-tip">Ctrl + Enter 快速发送</span>
                  <button
                    class="send-message-btn"
                    @click="sendTextMessage"
                    :disabled="!newMessage.trim() || isLoadingMessages"
                  >
                    <span class="btn-icon">{{ isLoadingMessages ? '⏳' : '📤' }}</span>
                    <span>{{ isLoadingMessages ? '发送中...' : '发送' }}</span>
                  </button>
                </div>
              </div>

              <!-- 等待状态 -->
              <div class="waiting-area" v-if="!isCurrentPlayerTurn">
                <div class="waiting-icon">⏳</div>
                <div class="waiting-text">等待 {{ currentSpeaker?.name }} 发言</div>
                <div class="waiting-subtitle">请耐心等待轮到您...</div>
              </div>
            </div>

            <!-- 语音模式 -->
            <div v-else class="voice-mode-section">
              <div class="speaker-info">
                <div class="speaker-avatar" :class="{ 'is-speaking': isSpeaking }">
                  <img
                    :src="currentSpeaker?.avatar"
                    :alt="currentSpeaker?.name"
                  />
                  <div class="role-indicator">🎭</div>
                  <div class="speaking-pulse" v-if="isSpeaking"></div>
                </div>
                <div class="speaker-details">
                  <div class="speaker-name">{{ currentSpeaker?.name }}</div>
                  <div class="speaker-role">{{ getCharacterRole(currentSpeaker) }}</div>
                  <div class="speech-status">
                    <span v-if="isCurrentPlayerTurn">轮到您发言</span>
                    <span v-else-if="isSpeaking">正在发言中...</span>
                    <span v-else>等待发言</span>
                  </div>
                </div>
              </div>

              <!-- 发言计时器 -->
              <div class="speech-timer">
                <div class="timer-circle">
                  <svg class="timer-svg" viewBox="0 0 100 100">
                    <circle
                      cx="50"
                      cy="50"
                      r="45"
                      fill="none"
                      stroke="rgba(59, 130, 246, 0.2)"
                      stroke-width="4"
                    />
                    <circle
                      cx="50"
                      cy="50"
                      r="45"
                      fill="none"
                      stroke="rgba(6, 182, 212, 0.8)"
                      stroke-width="4"
                      stroke-linecap="round"
                      :stroke-dasharray="circumference"
                      :stroke-dashoffset="strokeDashoffset"
                      class="timer-progress"
                    />
                  </svg>
                  <div class="timer-text">{{ remainingTime }}s</div>
                </div>
              </div>

              <!-- 语音控制 -->
              <div class="voice-controls">
                <button
                  class="voice-btn"
                  :class="{ 'recording': isRecording }"
                  @click="toggleRecording"
                  v-if="isCurrentPlayerTurn"
                  :disabled="isLoadingMessages"
                >
                  <span class="voice-icon">{{ isRecording ? '🔴' : '🎤' }}</span>
                  <span>{{ isRecording ? '停止录音' : '开始发言' }}</span>
                </button>
                <div class="voice-status" v-if="!isCurrentPlayerTurn">
                  <span class="waiting-icon">⏳</span>
                  <span>等待 {{ currentSpeaker?.name }} 发言</span>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 操作按钮 -->
        <div class="action-buttons">
          <button
            class="action-button dialogue-btn"
            @click="toggleInputMode"
            :class="{ 'text-mode': textMode, 'voice-mode': !textMode }"
            :disabled="!isCurrentPlayerTurn || isLoadingMessages"
          >
            <span class="btn-icon">{{ textMode ? '✍️' : '🎤' }}</span>
            <span>{{ textMode ? '文字模式' : '语音模式' }}</span>
          </button>
          <button
            class="action-button end-turn-btn"
            @click="endCurrentTurn"
            :disabled="!canEndTurn || isLoadingMessages"
          >
            <span class="btn-icon">✅</span>
            <span>结束发言</span>
          </button>
          <button
            class="action-button next-btn"
            @click="nextSpeaker"
            :disabled="!canProceedNext || isLoadingMessages"
          >
            <span class="btn-icon">➡️</span>
            <span>下一位</span>
          </button>
        </div>
      </div>

      <!-- 右侧边栏 -->
      <div class="sidebar">
        <!-- 发言顺序 -->
        <div class="speaking-order-panel">
          <div class="panel-header">
            <span class="panel-title">
              <span class="icon">🎯</span>
              <span>发言顺序</span>
            </span>
            <span class="turn-count">第{{ currentTurn }}轮</span>
          </div>
          <div class="order-list">
            <div
              v-for="(character, index) in speakingOrder"
              :key="character.id"
              :class="['order-item', {
                'current': index === currentSpeakerIndex,
                'finished': index < currentSpeakerIndex,
                'upcoming': index > currentSpeakerIndex
              }]"
            >
              <div class="order-number">{{ index + 1 }}</div>
              <div class="order-avatar">
                <img :src="character.avatar" :alt="character.name" />
                <div class="order-status" v-if="index === currentSpeakerIndex">🎤</div>
                <div class="order-status finished" v-else-if="index < currentSpeakerIndex">✅</div>
              </div>
              <div class="order-info">
                <div class="order-name">{{ character.name }}</div>
                <div class="order-role">{{ getCharacterRole(character) }}</div>
              </div>
            </div>
          </div>
        </div>

        <!-- 对话记录 -->
        <div class="chat-panel">
          <div class="panel-header">
            <span class="panel-title">
              <span class="icon">💬</span>
              <span>发言记录</span>
            </span>
            <span class="message-count">{{ messages.length }}条</span>
          </div>
          <div class="chat-messages" ref="chatContainer">
            <div
              v-for="message in messages"
              :key="message.id"
              :class="['game-message', message.message_type, {
                'own-message': message.character_id === theaterData.player_character_id
              }]"
            >
              <div class="message-time">{{ formatTime(message.timestamp) }}</div>
              <div class="message-content">
                <span v-if="message.character_name" class="message-player">{{ message.character_name }}：</span>
                <span class="message-text">{{ message.message }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 消息提示 -->
    <div v-if="errorMessage" class="toast toast-error">
      <span class="icon">⚠️</span>
      <span>{{ errorMessage }}</span>
      <button @click="errorMessage = ''" class="close-btn">×</button>
    </div>

    <div v-if="successMessage" class="toast toast-success">
      <span class="icon">✅</span>
      <span>{{ successMessage }}</span>
      <button @click="successMessage = ''" class="close-btn">×</button>
    </div>

    <!-- 加载状态 -->
    <div v-if="isLoadingMessages" class="loading-overlay">
      <div class="loading-spinner">
        <div class="spinner"></div>
        <span>AI角色正在回复...</span>
      </div>
    </div>

    <!-- 初始化状态 -->
    <div v-if="!isSessionInitialized" class="loading-overlay">
      <div class="loading-spinner">
        <div class="spinner"></div>
        <span>正在初始化剧场会话...</span>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, nextTick, watch, onMounted, onUnmounted } from 'vue'
import axios from 'axios'

// 类型定义
interface Character {
  id: string
  name: string
  description: string
  avatar: string
  selectedSkills: string[]
}

interface Message {
  id: string
  character_id: string
  character_name: string
  message: string
  timestamp: string
  message_type: 'system' | 'dialogue'
}

interface TheaterData {
  session_id: string
  theater_id: string
  theater_title: string
  node_id: string
  node_title: string
  node_content: string
  player_character_id: string
  all_characters: Character[]
  character_settings: any
  messages: Message[]
  created_at: string
  last_active: string
}

// API客户端配置
const chatApiClient = axios.create({
  baseURL: 'http://127.0.0.1:8801',
  timeout: 30000,
})

// 添加请求拦截器
chatApiClient.interceptors.request.use((config) => {
  console.log(`🌐 API请求: ${config.method?.toUpperCase()} ${config.url}`)
  return config
})

// 添加响应拦截器
chatApiClient.interceptors.response.use(
  (response) => {
    console.log(`✅ API响应成功: ${response.config.url}`)
    return response
  },
  (error) => {
    console.error(`❌ API请求失败:`, error)
    return Promise.reject(error)
  }
)

// 响应式数据
const currentSpeakerIndex = ref(0)
const currentTurn = ref(1)
const remainingTime = ref(60)
const speechTimeLimit = ref(60)
const isSpeaking = ref(false)
const isRecording = ref(false)
const textMode = ref(true) // 默认为文字模式

// 新增状态
const sessionId = ref<string>('')
const isSessionInitialized = ref(false)
const isLoadingMessages = ref(false)
const errorMessage = ref('')
const successMessage = ref('')
const recentlySpokeCharacters = ref<string[]>([])

// 剧场数据（保持原有数据结构）
const theaterData = reactive<TheaterData>({
  "session_id": "",
  "theater_id": "1617270848",
  "theater_title": "时光逆行：拯救未来",
  "node_id": "node-1",
  "node_title": "实验室的奇迹",
  "node_content": `<p>在2060年的未来，科技的飞速发展让人们在实验室中追求着无尽的可能性。<strong>艾米莉·温特</strong>正坐在高科技仪器环绕的实验室里，专注地研究着一台新型的时间机器。她的手指在触摸屏上灵巧地滑动，屏幕上闪烁着复杂的公式和图像，显示着时间旅行的理论模型。</p><br><p>"艾米莉，你准备好了吗？"<strong>教授威尔逊</strong>走了进来，脸上带着一丝关切。他的声音在实验室中显得格外清晰。"今天是我们实验的关键时刻。"</p><br><p>艾米莉抬起头，眼中闪烁着兴奋的光芒："我已经准备好了，教授！这次实验将验证我们对时间旅行理论的最后假设。只要一切顺利，我们就能真正揭开时间的面纱！"</p><br><p>她深吸一口气，重新专注于仪器面前的控制台，心中充满了期待与紧张。<em>时间机器的启动程序已经设置完毕</em>，她轻轻按下了启动按钮。随着一阵低沉的轰鸣声，仪器开始运转，周围的灯光闪烁不定，空气中弥漫着微弱的电流感。</p><br><p>就在这时，屏幕上突然出现了一幅奇异的画面——<strong>未来的景象</strong>在她眼前展开：高耸的建筑、飞天的交通工具、还有一片片污染的废墟，显然是某种灾难后的模样。</p><br><p>"这…这是什么？"艾米莉惊呼，心中掀起惊涛骇浪。她的手微微颤抖，无法相信眼前所见。</p><br><p>"注意保持冷静，艾米莉。"教授威尔逊在一旁提醒道，"我们可能正在探索未曾预见的时间线。"</p><br><p>然而，就在艾米莉准备深入研究这些数据时，实验室中的警报声骤然响起。她抬头一看，<strong>黑暗组织成员 - 维克特</strong>正悄然潜入，脸上挂着阴险的微笑。</p><br><p>"你们的实验果然有趣，聪明的物理学家。"维克特冷冷地说道，声音中带着嘲讽。他的目光扫视着仪器，仿佛在评估如何利用这项技术。"但可惜，你们不知道，这项技术的真正价值。"</p><br><p>艾米莉心中一紧，意识到危险逼近。她必须迅速作出选择：是继续观察这个未来的景象，还是立即采取行动，阻止维克特的计划？</p>`,
  "player_character_id": "char-3",
  "all_characters": [
    {
      "id": "char-1",
      "name": "艾米莉·温特",
      "description": "年轻的物理学家，充满了好奇心与探索精神。她在未来的实验室工作，致力于时间旅行的研究。艾米莉性格坚韧，善于分析问题，但有时也显得过于理想化。她的动机是拯救人类，防止即将到来的技术灾难。",
      "avatar": "https://ui-avatars.com/api/?name=艾米莉·温特&background=random&color=fff",
      "selectedSkills": [
        "时间旅行技术",
        "科学分析能力",
        "历史知识",
        "社交技巧",
        "逻辑推理"
      ]
    },
    {
      "id": "char-2",
      "name": "教授威尔逊",
      "description": "艾米莉的时间旅行导师，年长且智慧，拥有丰富的科学知识与经历，对时间旅行的伦理问题有深刻的理解。他性格沉稳，善于引导年轻的科学家思考，并提供宝贵的建议与帮助。",
      "avatar": "https://ui-avatars.com/api/?name=教授威尔逊&background=random&color=fff",
      "selectedSkills": [
        "危机管理",
        "实验室操作",
        "谈判技巧",
        "团队合作",
        "道德判断"
      ]
    },
    {
      "id": "char-3",
      "name": "黑暗组织成员 - 维克特",
      "description": "反派组织的核心成员，性格狡猾且野心勃勃。他对时间旅行有着极大的兴趣，企图利用时间机器来改变历史以谋求个人利益。维克特常常表现出冷酷的一面，善于操控他人。",
      "avatar": "https://ui-avatars.com/api/?name=黑暗组织成员 - 维克特&background=random&color=fff",
      "selectedSkills": [
        "历史事件记忆",
        "战略规划",
        "心理战术",
        "环境适应能力",
        "信息收集"
      ]
    },
    {
      "id": "char-4",
      "name": "年轻历史学家 - 亚历克斯",
      "description": "艾米莉在20世纪遇到的历史学家，性格开朗且富有同情心。他热爱历史，善于思考人类的命运，对艾米莉提供了极大的帮助。亚历克斯虽然年轻，但智慧与勇气并存。",
      "avatar": "https://ui-avatars.com/api/?name=年轻历史学家 - 亚历克斯&background=random&color=fff",
      "selectedSkills": [
        "隐蔽行动",
        "快速决策",
        "时间线解析",
        "编码与解码",
        "科技伦理讨论"
      ]
    }
  ],
  "character_settings": {},
  "messages": [],
  "created_at": "",
  "last_active": ""
})

// 计算属性
const allCharacters = computed(() => theaterData.all_characters)
const messages = computed(() => theaterData.messages)

const currentPlayerCharacter = computed(() => {
  return allCharacters.value.find(char => char.id === theaterData.player_character_id)
})

const speakingOrder = computed(() => {
  return allCharacters.value.sort((a, b) => a.id.localeCompare(b.id))
})

const currentSpeaker = computed(() => {
  return speakingOrder.value[currentSpeakerIndex.value]
})

const isCurrentPlayerTurn = computed(() => {
  return currentSpeaker.value?.id === theaterData.player_character_id
})

// 修改权限控制逻辑
const canSkipTurn = computed(() => {
  return isCurrentPlayerTurn.value && !isLoadingMessages.value
})

const canEndTurn = computed(() => {
  if (!isCurrentPlayerTurn.value || isLoadingMessages.value) return false

  if (textMode.value) {
    return newMessage.value.trim() !== '' || isSpeaking.value
  } else {
    return isSpeaking.value || isRecording.value
  }
})

const canProceedNext = computed(() => {
  return isCurrentPlayerTurn.value && !isSpeaking.value && !isRecording.value && !isLoadingMessages.value
})

const circumference = computed(() => 2 * Math.PI * 45)

const strokeDashoffset = computed(() => {
  const progress = remainingTime.value / speechTimeLimit.value
  return circumference.value * (1 - progress)
})

const newMessage = ref('')
const chatContainer = ref<HTMLElement>()

// 定时器
let timer: number | null = null

// 消息提示方法
const showSuccess = (message: string) => {
  successMessage.value = message
  setTimeout(() => {
    successMessage.value = ''
  }, 3000)
}

const showError = (message: string) => {
  errorMessage.value = message
  setTimeout(() => {
    errorMessage.value = ''
  }, 5000)
}

// 初始化聊天会话
const initializeChatSession = async () => {
  try {
    if (sessionId.value) {
      console.log('✅ 会话已存在:', sessionId.value)
      isSessionInitialized.value = true
      return
    }

    console.log('🚀 正在初始化聊天会话...')

    const response = await chatApiClient.post('/chat/start', {
      theater_title: theaterData.theater_title,
      node_id: theaterData.node_id,
      node_title: theaterData.node_title,
      node_content: theaterData.node_content,
      player_character_id: theaterData.player_character_id,
      all_characters: theaterData.all_characters,
      character_settings: theaterData.character_settings,
    })

    if (response.data.success) {
      sessionId.value = response.data.data.session_id
      theaterData.session_id = sessionId.value

      // 如果后端返回了初始消息，合并到现有消息中
      const initialMessages = response.data.data.initial_messages || []
      if (initialMessages.length > 0) {
        // 清空原有消息，使用后端返回的消息
        theaterData.messages = initialMessages
      }

      isSessionInitialized.value = true
      showSuccess('聊天会话初始化成功！')
      console.log('✅ 会话初始化成功:', sessionId.value)
    } else {
      throw new Error(response.data.message || '初始化会话失败')
    }
  } catch (error) {
    console.error('❌ 初始化聊天会话失败:', error)
    showError('初始化聊天会话失败，请重试')
    throw error
  }
}

// 发送消息并获取AI回复
const sendMessageAndGetAIReply = async (messageContent: string) => {
  if (!sessionId.value) {
    showError('会话未初始化，请刷新页面')
    return
  }

  try {
    isLoadingMessages.value = true

    console.log('📤 发送消息到AI:', messageContent)

    const response = await chatApiClient.post('/chat/message', {
      session_id: sessionId.value,
      message: messageContent,
    })

    if (response.data.success) {
      const newMessages = response.data.data.new_messages || []

      // 添加新消息到界面
      newMessages.forEach((msg: Message) => {
        theaterData.messages.push({
          id: msg.id,
          character_id: msg.character_id,
          character_name: msg.character_name,
          message: msg.message,
          timestamp: msg.timestamp,
          message_type: msg.message_type
        })
      })

      // 更新最近发言的角色
      updateRecentSpeakers(newMessages)

      console.log(`✅ 收到 ${newMessages.length} 条AI回复`)

      // 如果有AI回复，模拟其他角色的发言轮次
      if (newMessages.length > 1) {
        handleAICharacterReplies(newMessages.slice(1)) // 第一条是玩家消息
      }

    } else {
      throw new Error(response.data.message || '发送消息失败')
    }
  } catch (error) {
    console.error('❌ 发送消息失败:', error)
    showError('发送消息失败，请重试')
  } finally {
    isLoadingMessages.value = false
  }
}

// 处理AI角色回复
const handleAICharacterReplies = (aiMessages: Message[]) => {
  aiMessages.forEach((message, index) => {
    setTimeout(() => {
      // 找到对应的角色在发言顺序中的位置
      const characterIndex = speakingOrder.value.findIndex(char =>
        char.id === message.character_id || char.name === message.character_name
      )

      if (characterIndex !== -1) {
        // 模拟该角色发言
        console.log(`🎭 ${message.character_name} 开始发言`)

        // 更新当前发言者
        currentSpeakerIndex.value = characterIndex

        // 模拟发言过程
        setTimeout(() => {
          console.log(`✅ ${message.character_name} 发言完成`)

          // 如果不是最后一个AI回复，继续下一个
          if (index === aiMessages.length - 1) {
            // 所有AI角色发言完成，回到玩家回合
            nextPlayerTurn()
          }
        }, 2000) // 模拟2秒发言时间
      }
    }, index * 3000) // 每个角色间隔3秒发言
  })
}

// 切换到下一个玩家回合
const nextPlayerTurn = () => {
  // 找到下一个轮到玩家的位置
  let nextIndex = (currentSpeakerIndex.value + 1) % speakingOrder.value.length

  // 如果一轮结束，开始新一轮
  if (nextIndex === 0) {
    currentTurn.value++

    const newRoundMessage = {
      id: Date.now().toString(),
      character_id: 'system',
      character_name: '系统',
      message: `第${currentTurn.value}轮发言开始`,
      timestamp: new Date().toISOString(),
      message_type: 'system' as const
    }

    theaterData.messages.push(newRoundMessage)
  }

  currentSpeakerIndex.value = nextIndex

  // 重置状态
  remainingTime.value = speechTimeLimit.value
  isSpeaking.value = false
  isRecording.value = false
  newMessage.value = ''

  console.log(`🎯 轮到 ${currentSpeaker.value?.name} 发言`)
}

// 更新最近发言角色
const updateRecentSpeakers = (messages: Message[]) => {
  const speakers = messages
    .filter(msg => msg.message_type === 'dialogue' && msg.character_id !== theaterData.player_character_id)
    .map(msg => msg.character_id)

  // 更新最近发言角色列表
  speakers.forEach(speakerId => {
    if (!recentlySpokeCharacters.value.includes(speakerId)) {
      recentlySpokeCharacters.value.unshift(speakerId)
    }
  })

  // 保持最多5个最近发言角色
  recentlySpokeCharacters.value = recentlySpokeCharacters.value.slice(0, 5)
}

// 保存会话数据
const saveSessionData = async () => {
  if (!sessionId.value) {
    showError('会话未初始化，无法保存')
    return
  }

  try {
    console.log('💾 正在保存会话数据...')

    // 调用后端强制同步接口
    const response = await chatApiClient.post(`/chat/sync/force/${sessionId.value}`)

    if (response.data.success) {
      showSuccess('会话数据保存成功！')
      console.log('✅ 会话数据已保存到数据库')

      // 同时保存到本地存储
      const progressData = {
        session_id: sessionId.value,
        theater_data: theaterData,
        current_speaker_index: currentSpeakerIndex.value,
        current_turn: currentTurn.value,
        saved_at: new Date().toISOString(),
      }

      localStorage.setItem('theater_progress', JSON.stringify(progressData))
      localStorage.setItem(`theater_progress_${sessionId.value}`, JSON.stringify(progressData))

    } else {
      throw new Error(response.data.message || '保存失败')
    }
  } catch (error) {
    console.error('❌ 保存会话数据失败:', error)
    showError('保存会话数据失败，请重试')
  }
}

// 加载会话数据
const loadSessionData = async () => {
  try {
    // 先尝试从本地存储加载
    const savedData = localStorage.getItem('theater_progress')
    if (savedData) {
      const progressData = JSON.parse(savedData)

      if (progressData.session_id) {
        sessionId.value = progressData.session_id
        theaterData.session_id = sessionId.value
        currentSpeakerIndex.value = progressData.current_speaker_index || 0
        currentTurn.value = progressData.current_turn || 1

        console.log('✅ 从本地存储加载会话数据成功')
      }
    }

    // 然后尝试从后端加载最新数据
    if (sessionId.value) {
      const response = await chatApiClient.get(`/chat/history/${sessionId.value}`)

      if (response.data.success) {
        const historyData = response.data.data

        // 更新消息列表
        if (historyData.messages && Array.isArray(historyData.messages)) {
          theaterData.messages = historyData.messages
        }

        console.log('✅ 从后端加载会话历史成功')
      }
    }
  } catch (error) {
    console.error('❌ 加载会话数据失败:', error)
    // 加载失败不影响游戏继续
  }
}

// 方法
const formatTime = (timestamp: string) => {
  const date = new Date(timestamp)
  return date.toLocaleTimeString('zh-CN', {
    hour: '2-digit',
    minute: '2-digit'
  })
}

const getCharacterRole = (character: Character | null) => {
  if (!character) return '未知角色'

  if (character.name.includes('艾米莉')) return '物理学家'
  if (character.name.includes('教授')) return '导师'
  if (character.name.includes('维克特')) return '反派'
  if (character.name.includes('亚历克斯')) return '历史学家'

  return '角色'
}

const getCurrentSpeakerName = () => {
  return currentSpeaker.value?.name || '未知'
}

const startTimer = () => {
  if (timer) clearInterval(timer)
  remainingTime.value = speechTimeLimit.value

  timer = setInterval(() => {
    remainingTime.value--
    if (remainingTime.value <= 0) {
      // 只有轮到当前玩家时才自动结束
      if (isCurrentPlayerTurn.value) {
        endCurrentTurn()
      }
    }
  }, 1000)
}

const stopTimer = () => {
  if (timer) {
    clearInterval(timer)
    timer = null
  }
}

// 切换输入模式
const toggleInputMode = () => {
  // 只有轮到当前玩家时才能切换模式
  if (!isCurrentPlayerTurn.value || isLoadingMessages.value) return

  textMode.value = !textMode.value

  // 切换模式时重置状态
  if (textMode.value) {
    // 切换到文字模式
    isRecording.value = false
    isSpeaking.value = false
    stopTimer()
  } else {
    // 切换到语音模式
    newMessage.value = ''
    if (isCurrentPlayerTurn.value) {
      startTimer()
    }
  }
}

const toggleRecording = () => {
  if (!isCurrentPlayerTurn.value || textMode.value || isLoadingMessages.value) return

  isRecording.value = !isRecording.value
  isSpeaking.value = isRecording.value

  if (isRecording.value) {
    startTimer()
    console.log('开始录音...')
  } else {
    stopTimer()
    console.log('停止录音...')
  }
}

const endCurrentTurn = async () => {
  // 只有轮到当前玩家时才能结束发言
  if (!isCurrentPlayerTurn.value || isLoadingMessages.value) return
  if (!canEndTurn.value) return

  // 在文字模式下，发送消息
  if (textMode.value && newMessage.value.trim()) {
    await sendTextMessage()
    return
  }

  // 停止录音和计时
  isRecording.value = false
  isSpeaking.value = false
  stopTimer()

  // 添加发言结束记录
  const message = {
    id: Date.now().toString(),
    character_id: currentSpeaker.value.id,
    character_name: currentSpeaker.value.name,
    message: '发言结束',
    timestamp: new Date().toISOString(),
    message_type: 'system' as const
  }

  theaterData.messages.push(message)

  // 触发AI轮次
  setTimeout(() => {
    triggerAIRound()
  }, 1000)
}

// 触发AI角色轮次
const triggerAIRound = async () => {
  // 发送一个特殊消息来触发AI回复
  if (sessionId.value) {
    try {
      const response = await chatApiClient.post('/chat/message', {
        session_id: sessionId.value,
        message: '[CONTINUE_DIALOGUE]', // 特殊标记，提示AI继续对话
      })

      if (response.data.success) {
        const newMessages = response.data.data.new_messages || []

        // 过滤掉特殊消息，只保留AI回复
        const aiReplies = newMessages.filter((msg: Message) =>
          msg.message !== '[CONTINUE_DIALOGUE]' && msg.character_id !== theaterData.player_character_id
        )

        if (aiReplies.length > 0) {
          // 添加AI回复到消息列表
          aiReplies.forEach((msg: Message) => {
            theaterData.messages.push(msg)
          })

          // 处理AI角色发言轮次
          handleAICharacterReplies(aiReplies)
        } else {
          // 如果没有AI回复，直接进入下一轮
          nextPlayerTurn()
        }
      }
    } catch (error) {
      console.error('❌ 触发AI轮次失败:', error)
      // 如果AI请求失败，也要继续游戏流程
      nextPlayerTurn()
    }
  }
}

const nextSpeaker = () => {
  // 只有轮到当前玩家时才能切换到下一位
  if (!isCurrentPlayerTurn.value || isLoadingMessages.value) return

  nextPlayerTurn()
}

const sendTextMessage = async () => {
  if (!newMessage.value.trim() || !isCurrentPlayerTurn.value || isLoadingMessages.value) return

  const messageContent = newMessage.value.trim()
  newMessage.value = '' // 立即清空输入框

  // 先添加玩家消息到界面
  const playerMessage = {
    id: Date.now().toString(),
    character_id: theaterData.player_character_id,
    character_name: currentPlayerCharacter.value?.name || '玩家',
    message: messageContent,
    timestamp: new Date().toISOString(),
    message_type: 'dialogue' as const
  }

  theaterData.messages.push(playerMessage)
  isSpeaking.value = true

  // 发送到后端并获取AI回复
  await sendMessageAndGetAIReply(messageContent)
}

const handleSkipTurn = () => {
  // 只有轮到当前玩家时才能跳过
  if (!isCurrentPlayerTurn.value || isLoadingMessages.value) return

  // 添加跳过发言的记录
  const message = {
    id: Date.now().toString(),
    character_id: theaterData.player_character_id,
    character_name: currentPlayerCharacter.value?.name || '玩家',
    message: '跳过了本轮发言',
    timestamp: new Date().toISOString(),
    message_type: 'system' as const
  }

  theaterData.messages.push(message)

  // 直接进入下一位
  nextPlayerTurn()
}

const handleSettings = async () => {
  await saveSessionData()
}

const handleRules = () => {
  console.log('查看剧情')
}

// 监听聊天消息变化，自动滚动
watch(() => messages.value.length, () => {
  nextTick(() => {
    if (chatContainer.value) {
      chatContainer.value.scrollTop = chatContainer.value.scrollHeight
    }
  })
})

// 监听当前发言者变化
watch(currentSpeaker, (newSpeaker) => {
  if (!newSpeaker) return

  console.log(`轮到 ${newSpeaker?.name} 发言`)

  const message = {
    id: Date.now().toString(),
    character_id: 'system',
    character_name: '系统',
    message: `轮到 ${newSpeaker?.name} 发言`,
    timestamp: new Date().toISOString(),
    message_type: 'system' as const
  }

  theaterData.messages.push(message)
})

onMounted(async () => {
  console.log('🎭 剧场体验开始:', theaterData.theater_title)

  try {
    // 加载已保存的会话数据
    await loadSessionData()

    // 初始化聊天会话
    await initializeChatSession()

    console.log('✅ 剧场初始化完成')
  } catch (error) {
    console.error('❌ 剧场初始化失败:', error)
    showError('剧场初始化失败，请刷新页面重试')
  }
})

onUnmounted(async () => {
  stopTimer()

  // 保存当前进度
  if (sessionId.value) {
    try {
      await saveSessionData()
    } catch (error) {
      console.error('❌ 退出时保存失败:', error)
    }
  }
})
</script>

<style scoped>
/* 样式部分保持不变，只添加一些新的样式 */
.werewolf-room {
  min-height: 94vh;
  background: linear-gradient(135deg, rgba(59, 130, 246, 0.05) 0%, rgba(6, 182, 212, 0.05) 100%);
  padding: 3vh 5vw;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
  color: #1e293b;
  position: relative;
}

.werewolf-room::before {
  content: '';
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(135deg, rgba(248, 250, 252, 0.95) 0%, rgba(241, 245, 249, 0.95) 50%, rgba(248, 250, 252, 0.95) 100%);
  z-index: -1;
}

/* 顶部房间信息栏 */
.room-header {
  background: rgba(255, 255, 255, 0.7);
  backdrop-filter: blur(20px);
  border: 1px solid rgba(59, 130, 246, 0.1);
  border-radius: 16px;
  padding: 16px 20px;
  margin-bottom: 16px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 4px 20px rgba(59, 130, 246, 0.08);
}

.room-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.room-avatar {
  width: 48px;
  height: 48px;
  background: linear-gradient(135deg, rgba(59, 130, 246, 0.8) 0%, rgba(6, 182, 212, 0.8) 100%);
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
  color: white;
  box-shadow: 0 4px 12px rgba(59, 130, 246, 0.2);
}

.room-title {
  font-size: 16px;
  font-weight: 600;
  color: #1e293b;
  margin-bottom: 4px;
}

.room-status {
  display: flex;
  gap: 12px;
  font-size: 12px;
  color: #64748b;
}

.status-item.phase {
  color: rgba(6, 182, 212, 0.8);
  font-weight: 500;
}

.status-dot {
  width: 6px;
  height: 6px;
  background: rgba(6, 182, 212, 0.8);
  border-radius: 50%;
  animation: pulse-dot 2s infinite;
}

.room-actions {
  display: flex;
  gap: 8px;
}

.action-btn {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 8px 12px;
  border-radius: 10px;
  border: none;
  font-size: 12px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s;
}

.action-btn.secondary {
  background: rgba(59, 130, 246, 0.08);
  color: #475569;
  border: 1px solid rgba(59, 130, 246, 0.2);
}

.action-btn.secondary:hover:not(:disabled) {
  background: rgba(59, 130, 246, 0.12);
  border-color: rgba(59, 130, 246, 0.3);
}

.action-btn.primary {
  background: linear-gradient(135deg, rgba(59, 130, 246, 0.8) 0%, rgba(6, 182, 212, 0.8) 100%);
  color: white;
}

.action-btn.primary:hover:not(:disabled) {
  background: linear-gradient(135deg, rgba(59, 130, 246, 0.9) 0%, rgba(6, 182, 212, 0.9) 100%);
}

.action-btn:disabled {
  opacity: 0.4;
  cursor: not-allowed;
  background: rgba(156, 163, 175, 0.3) !important;
  color: #9ca3af !important;
  border-color: rgba(156, 163, 175, 0.2) !important;
}

/* 主内容区域 */
.main-content {
  display: grid;
  grid-template-columns: 1fr 300px;
  gap: 16px;
}

/* 左侧发言区域 */
.speech-area {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.current-speaker-stage {
  background: rgba(255, 255, 255, 0.6);
  backdrop-filter: blur(20px);
  border: 1px solid rgba(59, 130, 246, 0.15);
  border-radius: 20px;
  padding: 24px;
  display: flex;
  gap: 24px;
  box-shadow: 0 8px 32px rgba(59, 130, 246, 0.08);
}

/* 左侧剧情内容区域 */
.script-section {
  flex: 1;
  min-width: 0;
}

.script-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 16px;
  padding-bottom: 8px;
  border-bottom: 1px solid rgba(59, 130, 246, 0.15);
}

.script-icon {
  font-size: 18px;
}

.script-title {
  font-size: 18px;
  font-weight: 600;
  color: rgba(6, 182, 212, 0.9);
}

.script-content {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.script-description {
  font-size: 14px;
  color: #475569;
  line-height: 1.6;
  max-height: 300px;
  overflow-y: auto;
  padding-right: 8px;
}

.script-description::-webkit-scrollbar {
  width: 4px;
}

.script-description::-webkit-scrollbar-track {
  background: rgba(59, 130, 246, 0.08);
}

.script-description::-webkit-scrollbar-thumb {
  background: rgba(59, 130, 246, 0.3);
  border-radius: 2px;
}

.player-role-info {
  background: rgba(59, 130, 246, 0.06);
  border-radius: 12px;
  padding: 12px;
  border: 1px solid rgba(59, 130, 246, 0.15);
}

.roles-title {
  font-size: 13px;
  font-weight: 600;
  color: rgba(59, 130, 246, 0.8);
  margin-bottom: 8px;
}

.current-role {
  display: flex;
  gap: 12px;
  align-items: flex-start;
}

.role-avatar {
  width: 48px;
  height: 48px;
  border-radius: 50%;
  overflow: hidden;
  flex-shrink: 0;
  border: 2px solid rgba(59, 130, 246, 0.2);
}

.role-avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.role-details {
  flex: 1;
}

.role-name {
  font-size: 14px;
  font-weight: 600;
  color: #1e293b;
  margin-bottom: 4px;
}

.role-desc {
  font-size: 12px;
  color: #64748b;
  line-height: 1.4;
  margin-bottom: 8px;
}

.role-skills {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.skills-label {
  font-size: 11px;
  color: #64748b;
}

.skills-list {
  display: flex;
  gap: 4px;
  flex-wrap: wrap;
}

.skill-tag {
  background: rgba(59, 130, 246, 0.12);
  color: rgba(59, 130, 246, 0.8);
  padding: 2px 6px;
  border-radius: 4px;
  font-size: 10px;
  font-weight: 500;
}

/* 右侧发言角色区域 */
.speaker-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 16px;
  min-width: 200px;
}

/* 文字模式样式 */
.text-mode-section {
  display: flex;
  flex-direction: column;
  gap: 16px;
  width: 100%;
}

.text-input-area {
  background: rgba(59, 130, 246, 0.04);
  border-radius: 12px;
  padding: 16px;
  border: 1px solid rgba(59, 130, 246, 0.1);
}

.input-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 12px;
}

.input-icon {
  font-size: 16px;
}

.input-title {
  font-size: 14px;
  font-weight: 600;
  color: #1e293b;
}

.text-input {
  width: 100%;
  min-height: 80px;
  padding: 12px;
  border: 1px solid rgba(59, 130, 246, 0.2);
  border-radius: 8px;
  font-size: 14px;
  line-height: 1.5;
  resize: vertical;
  outline: none;
  background: rgba(255, 255, 255, 0.8);
  color: #1e293b;
  font-family: inherit;
}

.text-input::placeholder {
  color: #64748b;
}

.text-input:focus {
  border-color: rgba(59, 130, 246, 0.4);
  background: rgba(255, 255, 255, 0.9);
}

.text-input:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.input-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 12px;
}

.input-tip {
  font-size: 11px;
  color: #64748b;
}

.send-message-btn {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 8px 16px;
  background: linear-gradient(135deg, rgba(59, 130, 246, 0.8) 0%, rgba(6, 182, 212, 0.8) 100%);
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 12px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s;
}

.send-message-btn:hover:not(:disabled) {
  background: linear-gradient(135deg, rgba(59, 130, 246, 0.9) 0%, rgba(6, 182, 212, 0.9) 100%);
}

.send-message-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.waiting-area {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
  padding: 20px;
  background: rgba(59, 130, 246, 0.04);
  border-radius: 12px;
  border: 1px solid rgba(59, 130, 246, 0.1);
}

.waiting-icon {
  font-size: 24px;
}

.waiting-text {
  font-size: 14px;
  color: #64748b;
  font-weight: 500;
}

.waiting-subtitle {
  font-size: 12px;
  color: #94a3b8;
  text-align: center;
}

/* 语音模式样式（保持原有样式） */
.voice-mode-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 16px;
  width: 100%;
}

.speaker-info {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 12px;
  text-align: center;
}

.speaker-avatar {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
  border: 3px solid rgba(59, 130, 246, 0.3);
  overflow: hidden;
  transition: all 0.3s ease;
}

.speaker-avatar.is-speaking {
  border-color: rgba(6, 182, 212, 0.8);
  box-shadow: 0 0 20px rgba(6, 182, 212, 0.3);
}

.speaker-avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.role-indicator {
  position: absolute;
  top: -8px;
  right: -8px;
  width: 24px;
  height: 24px;
  background: rgba(59, 130, 246, 0.8);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
  color: white;
}

.speaking-pulse {
  position: absolute;
  top: -6px;
  left: -6px;
  right: -6px;
  bottom: -6px;
  border: 2px solid rgba(6, 182, 212, 0.8);
  border-radius: 50%;
  animation: pulse-ring 2s infinite;
}

@keyframes pulse-ring {
  0% {
    transform: scale(1);
    opacity: 1;
  }
  100% {
    transform: scale(1.2);
    opacity: 0;
  }
}

.speaker-details {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.speaker-name {
  font-size: 16px;
  font-weight: 600;
  color: #1e293b;
}

.speaker-role {
  font-size: 12px;
  color: rgba(59, 130, 246, 0.7);
}

.speech-status {
  font-size: 11px;
  color: #64748b;
}

.speech-timer {
  display: flex;
  align-items: center;
  justify-content: center;
}

.timer-circle {
  position: relative;
  width: 80px;
  height: 80px;
}

.timer-svg {
  width: 100%;
  height: 100%;
  transform: rotate(-90deg);
}

.timer-progress {
  transition: stroke-dashoffset 1s linear;
  stroke: rgba(6, 182, 212, 0.8);
}

.timer-text {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  font-size: 16px;
  font-weight: 600;
  color: #1e293b;
}

/* 语音控制 */
.voice-controls {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
}

.voice-btn {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 12px 20px;
  border-radius: 12px;
  border: none;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
  background: linear-gradient(135deg, rgba(16, 185, 129, 0.8) 0%, rgba(5, 150, 105, 0.8) 100%);
  color: white;
  box-shadow: 0 4px 12px rgba(16, 185, 129, 0.2);
}

.voice-btn.recording {
  background: linear-gradient(135deg, rgba(239, 68, 68, 0.8) 0%, rgba(220, 38, 38, 0.8) 100%);
  box-shadow: 0 4px 12px rgba(239, 68, 68, 0.2);
  animation: recording-pulse 1s infinite;
}

.voice-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

@keyframes recording-pulse {
  0%, 100% {
    transform: scale(1);
  }
  50% {
    transform: scale(1.05);
  }
}

.voice-status {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 16px;
  background: rgba(59, 130, 246, 0.08);
  border-radius: 12px;
  font-size: 12px;
  color: #64748b;
}

/* 操作按钮 */
.action-buttons {
  display: flex;
  gap: 12px;
  justify-content: center;
}

.action-button {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 12px 20px;
  border-radius: 12px;
  border: none;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s;
}

.dialogue-btn {
  background: linear-gradient(135deg, rgba(59, 130, 246, 0.8) 0%, rgba(29, 78, 216, 0.8) 100%);
  color: white;
  border: 2px solid transparent;
}

.dialogue-btn.text-mode {
  background: linear-gradient(135deg, rgba(79, 70, 229, 0.8) 0%, rgba(99, 102, 241, 0.8) 100%);
  border-color: rgba(79, 70, 229, 0.3);
}

.dialogue-btn.voice-mode {
  background: linear-gradient(135deg, rgba(16, 185, 129, 0.8) 0%, rgba(5, 150, 105, 0.8) 100%);
  border-color: rgba(16, 185, 129, 0.3);
}

.end-turn-btn {
  background: linear-gradient(135deg, rgba(245, 158, 11, 0.8) 0%, rgba(217, 119, 6, 0.8) 100%);
  color: white;
}

.next-btn {
  background: linear-gradient(135deg, rgba(5, 150, 105, 0.8) 0%, rgba(4, 120, 87, 0.8) 100%);
  color: white;
}

.action-button:disabled {
  opacity: 0.4;
  cursor: not-allowed;
  background: rgba(156, 163, 175, 0.3) !important;
  color: #9ca3af !important;
  border-color: rgba(156, 163, 175, 0.2) !important;
}

/* 右侧边栏 */
.sidebar {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.speaking-order-panel,
.chat-panel {
  background: rgba(255, 255, 255, 0.6);
  backdrop-filter: blur(20px);
  border: 1px solid rgba(59, 130, 246, 0.15);
  border-radius: 16px;
  padding: 16px;
}

.panel-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.panel-title {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 14px;
  font-weight: 600;
  color: #1e293b;
}

.turn-count {
  background: rgba(59, 130, 246, 0.12);
  color: rgba(59, 130, 246, 0.8);
  padding: 4px 8px;
  border-radius: 8px;
  font-size: 11px;
  font-weight: 500;
}

.message-count {
  background: rgba(16, 185, 129, 0.12);
  color: rgba(16, 185, 129, 0.8);
  padding: 4px 8px;
  border-radius: 8px;
  font-size: 11px;
  font-weight: 500;
}

/* 发言顺序列表 */
.order-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.order-item {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px;
  border-radius: 8px;
  transition: all 0.2s;
  border: 1px solid rgba(59, 130, 246, 0.1);
}

.order-item.current {
  background: rgba(6, 182, 212, 0.1);
  border-color: rgba(6, 182, 212, 0.2);
}

.order-item.finished {
  opacity: 0.6;
  background: rgba(16, 185, 129, 0.08);
}

.order-item.upcoming {
  opacity: 0.8;
}

.order-number {
  width: 20px;
  height: 20px;
  background: rgba(59, 130, 246, 0.15);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 10px;
  font-weight: 600;
  flex-shrink: 0;
  color: rgba(59, 130, 246, 0.8);
}

.order-avatar {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  overflow: hidden;
  position: relative;
  flex-shrink: 0;
  border: 1px solid rgba(59, 130, 246, 0.2);
}

.order-avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.order-status {
  position: absolute;
  top: -4px;
  right: -4px;
  width: 16px;
  height: 16px;
  background: rgba(59, 130, 246, 0.8);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 8px;
  color: white;
}

.order-status.finished {
  background: rgba(16, 185, 129, 0.8);
}

.order-info {
  flex: 1;
  min-width: 0;
}

.order-name {
  font-size: 12px;
  font-weight: 500;
  color: #1e293b;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.order-role {
  font-size: 10px;
  color: #64748b;
}

/* 聊天区域 */
.chat-panel {
  flex: 1;
  display: flex;
  flex-direction: column;
  min-height: 0;
}

.chat-messages {
  flex: 1;
  max-height: 300px;
  overflow-y: auto;
  margin-bottom: 12px;
  padding-right: 4px;
}

.chat-messages::-webkit-scrollbar {
  width: 3px;
}

.chat-messages::-webkit-scrollbar-track {
  background: rgba(59, 130, 246, 0.08);
}

.chat-messages::-webkit-scrollbar-thumb {
  background: rgba(59, 130, 246, 0.3);
  border-radius: 2px;
}

.game-message {
  margin-bottom: 8px;
  padding: 8px;
  border-radius: 8px;
  font-size: 12px;
  line-height: 1.4;
}

.game-message.system {
  background: rgba(6, 182, 212, 0.1);
  border: 1px solid rgba(6, 182, 212, 0.2);
}

.game-message.dialogue {
  background: rgba(59, 130, 246, 0.1);
  border: 1px solid rgba(59, 130, 246, 0.2);
}

.game-message.own-message {
  background: rgba(59, 130, 246, 0.15);
  border: 1px solid rgba(59, 130, 246, 0.3);
}

.message-time {
  font-size: 10px;
  color: #64748b;
  margin-bottom: 2px;
}

.message-player {
  font-weight: 600;
  color: rgba(6, 182, 212, 0.8);
}

.message-text {
  color: #475569;
}

/* 消息提示样式 */
.toast {
  position: fixed;
  top: 20px;
  right: 20px;
  background: white;
  border-radius: 12px;
  padding: 12px 16px;
  display: flex;
  align-items: center;
  gap: 8px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
  z-index: 1000;
  animation: slideIn 0.3s ease;
  max-width: 400px;
}

.toast-error {
  border-left: 4px solid #ef4444;
}

.toast-success {
  border-left: 4px solid #10b981;
}

.close-btn {
  background: none;
  border: none;
  cursor: pointer;
  font-size: 16px;
  color: #6b7280;
  padding: 0;
  margin-left: auto;
}

.close-btn:hover {
  color: #374151;
}

/* 加载状态样式 */
.loading-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 999;
  backdrop-filter: blur(4px);
}

.loading-spinner {
  background: white;
  border-radius: 12px;
  padding: 24px;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 12px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.2);
}

.spinner {
  width: 32px;
  height: 32px;
  border: 3px solid #f3f4f6;
  border-top: 3px solid #3b82f6;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes slideIn {
  from {
    transform: translateX(100%);
    opacity: 0;
  }
  to {
    transform: translateX(0);
    opacity: 1;
  }
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

@keyframes pulse-dot {
  0%, 100% { opacity: 1; }
  50% { opacity: 0.5; }
}

/* 响应式设计 */
@media (max-width: 1024px) {
  .main-content {
    grid-template-columns: 1fr;
  }

  .sidebar {
    order: -1;
  }

  .current-speaker-stage {
    flex-direction: column;
    gap: 16px;
  }

  .speaker-section {
    min-width: auto;
  }
}

@media (max-width: 768px) {
  .werewolf-room {
    padding: 12px;
  }

  .room-header {
    flex-direction: column;
    gap: 12px;
    padding: 12px 16px;
  }

  .action-buttons {
    flex-direction: column;
  }

  .current-role {
    flex-direction: column;
    text-align: center;
  }
}
</style>
